<?php

declare(strict_types=1);

namespace MultiWorker;

use MultiWorker\Exception\ProcessException;

class Deamon extends Process
{
    /**
     * Deamon Constructor.
     * 
     * @return void
     */
    public function __construct (array $config = [])
    {
        parent::__construct($config);
    }

    /**
     * deamon run.
     *
     * @return void
     */
    public function run (): void
    {
        $pid = pcntl_fork();
        switch ($pid) {
            case -1:
                throw new ProcessException('fork process error.');
                break;
            case 0:
                $sid = posix_setsid();
                if ($sid <= 0) {
                    throw new ProcessException("set sid error.");
                }
                if (chdir('/') === false) {
                    throw new ProcessException("chdir change dir path error.");
                }
                umask(0);
                fclose(STDIN);
                fclose(STDOUT);
                fclose(STDERR);
                break;
            default:
                // 父进程
                exit;
                break;
        }
    }
}